import { setState } from './index'
import { apiSignUp, apiLogin, apiGetUserInfo, apiUpdateUserInfo } from '@/api/user'

const state = {
  isLogin: false,
  token: null,
  username: '',
  nickname: '',
  avatar: '',
  email: '',
  conscode: 0
}
const mutations = { setState }
const actions = {
  async signUp({ state, commit }, { email, password }) {
    return new Promise((resolve, reject) => {
      apiSignUp({ email, password }).then(res => {
        if (res.success) {
          const { token, username, nickname, email } = res.data
          commit('setState', {
            isLogin: true,
            token,
            username,
            nickname,
            email
          })
          resolve()
        }
      })
    })
  },

  login({ state, commit }, { username, password }) {
    return new Promise((resolve, reject) => {
      apiLogin({ username, password }).then(res => {
        if (res.success) {
          commit('setState', { isLogin: true, token: res.data, username })
          resolve()
        } else {
          reject(res.error)
        }
      })
    })
  },

  logout({ commit }) {
    return new Promise(resolve => {
      commit('setState', {
        isLogin: false,
        token: null,
        username: '',
        nickname: '',
        avatar: '',
        email: '',
        conscode: 0
      })
      resolve()
    })
  },

  getUser({ state, commit }) {
    apiGetUserInfo({ token: state.token, username: state.username }).then(res => {
      if (res.success) {
        console.log('user info', res.data)
        const { username, email, nickname, avatar, conscode } = res.data
        commit('setState', {
          username,
          email,
          nickname,
          avatar,
          conscode
        })
      }
    })
  },

  updateUser({ state, commit }, params) {
    const data = { ...state, ...params }
    delete data.isLogin
    return new Promise(resolve => {
      apiUpdateUserInfo(data).then(res => {
        if (res.success) {
          commit('setState', { ...res.data })
          resolve()
        }
      })
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
